package com.xmut.bs.handaccount.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.base.CommonListActivity;
import com.xmut.bs.handaccount.bean.AnimationType;
import com.xmut.bs.handaccount.bmob.Collection;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.RoundCornersTransformation;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.UpdateListener;

import static android.support.v7.widget.helper.ItemTouchHelper.ACTION_STATE_DRAG;
import static android.support.v7.widget.helper.ItemTouchHelper.ACTION_STATE_IDLE;
import static com.xmut.bs.handaccount.base.Constants.PARAM_EDIT;

/**
 * Description
 * Created by Dollkey on 2018/4/11.
 */

public class CollectionManageActivity extends CommonListActivity<Collection> {

    private ItemTouchHelper mItemTouchHelper;

    @Override
    public void afterInit() {
        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            RecyclerView.ViewHolder lastDragViewHolder;

            /**
             * 当用户长按后，会触发拖拽的选中效果，viewHolder就是当前的选中
             * @param viewHolder
             * @param actionState 取下面中的值
             *                    {@link ItemTouchHelper#ACTION_STATE_IDLE},
             *                    {@link ItemTouchHelper#ACTION_STATE_SWIPE},
             *                    {@link ItemTouchHelper#ACTION_STATE_DRAG}.
             */
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
                //如果状态为拖拽，说明选中了
                //我在xml里面写的scale都为0.8 我们需要把当前的视图放大一下，所以设置为1就可以了
                if (viewHolder != null && actionState == ACTION_STATE_DRAG) {
                    lastDragViewHolder = viewHolder;
//                    viewHolder.itemView.setScaleX(0.9f);
//                    viewHolder.itemView.setScaleY(0.9f);
                    AnimatorSet mMoveAnimator = new AnimatorSet();
                    mMoveAnimator.playTogether(
                            ObjectAnimator.ofFloat(viewHolder.itemView, AnimationType.SCALE_X.getTypeName(), 1, 1.1f),
                            ObjectAnimator.ofFloat(viewHolder.itemView, AnimationType.SCALE_Y.getTypeName(), 1, 1.1f));
                    mMoveAnimator.setDuration(500);
                    mMoveAnimator.start();
                }

                //ACTION_STATE_IDLE就是松开了，把大小改为原状
                if (lastDragViewHolder != null && actionState == ACTION_STATE_IDLE) {
//                    lastDragViewHolder.itemView.setScaleX(1);
//                    lastDragViewHolder.itemView.setScaleY(1);
                    AnimatorSet mMoveAnimator = new AnimatorSet();
                    mMoveAnimator.playTogether(
                            ObjectAnimator.ofFloat(lastDragViewHolder.itemView, AnimationType.SCALE_X.getTypeName(), 1.1f, 1),
                            ObjectAnimator.ofFloat(lastDragViewHolder.itemView, AnimationType.SCALE_Y.getTypeName(), 1.1f, 1));
                    mMoveAnimator.setDuration(500);
                    mMoveAnimator.start();
                    lastDragViewHolder = null;
                    //是为了实现RecyclerView自动回位的，实现在后面给出
                }
            }

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof GridLayoutManager) {// GridLayoutManager
                    // flag如果值是0，相当于这个功能被关闭
                    int dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    int swipeFlag = 0;
                    // create make
                    return makeMovementFlags(dragFlag, swipeFlag);
                } else if (layoutManager instanceof LinearLayoutManager) {// linearLayoutManager
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    int orientation = linearLayoutManager.getOrientation();
                    int dragFlag = 0;
                    int swipeFlag = 0;
                    // 为了方便理解，相当于分为横着的ListView和竖着的ListView
                    if (orientation == LinearLayoutManager.HORIZONTAL) {// 如果是横向的布局
                        swipeFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    } else if (orientation == LinearLayoutManager.VERTICAL) {// 如果是竖向的布局，相当于ListView
                        dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        swipeFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    }
                    return makeMovementFlags(dragFlag, swipeFlag);
                }
                return 0;
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                if (mComList != null) {
                    // 更换数据源中的数据Item的位置
                    Collections.swap(mComList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                    // 更新UI中的Item的位置，主要是给用户看到交互效果
                    mAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                    return true;
                }
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                final Collection adv = mComList.get(viewHolder.getAdapterPosition());
                adv.delete(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            showToast("删除成功");
                            mComList.remove(adv);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        });
        mItemTouchHelper.attachToRecyclerView(mRecycleView);
    }

    @Override
    protected String getSubTitle() {
        return "合辑管理";
    }

    @Override
    protected RecyclerView.ItemDecoration getItemDecoration() {
        return new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8), DividerItemDecoration.BOTH_SET, 3,false,
                getResources().getColor(R.color.white));
    }

    @NonNull
    @Override
    protected RecyclerView.LayoutManager getRvLayoutManager() {
        return new GridLayoutManager(mContext,3);
    }

    @Override
    protected RecyclerView.Adapter getAdapter(List<Collection> comList) {
        return new CommonAdapter<Collection>(mContext, R.layout.item_type, comList) {
            @Override
            protected void convert(final ViewHolder holder, final Collection adv, int position) {
                View view = holder.getConvertView();
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivityForResult(AddCollectionActivity.class, new Intent().putExtra(PARAM_EDIT, adv), 1);
                    }
                });
                holder.getView(R.id.drag_iv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mItemTouchHelper.startDrag(holder);
                    }
                });
                holder.setVisible(R.id.drag_iv, true);
                holder.setText(R.id.tv_type, adv.getName());
                ImageView img = holder.getView(R.id.iv_type);
                GlideApp.with(img).load(adv.getImgUrl()).transform(new MultiTransformation<>(new CenterCrop(),new RoundCornersTransformation(mContext,
                        DisplayUtils.dp2px(mContext, 4), RoundCornersTransformation.CornerType.ALL))).into(img);
            }
        };
    }

    @Override
    public void getData(int pageNo, int pageSize) {
        if (pageNo != 0) return;
        mBmobQuery.order("order");
        mBmobQuery.findObjects(new FindListener<Collection>() {
            @Override
            public void done(List<Collection> list, BmobException e) {
                if (e == null) {
                    showList(list);
                } else {
                    showError("请求失败：" + e.getMessage());
                }
            }
        });
    }

    @Override
    protected void initParams(Intent intent) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                startActivityForResult(AddCollectionActivity.class, 1);
                break;
            case R.id.action_save:
                saveOrder();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void saveOrder() {
        int size = mComList.size();
        for (int i = 0; i < size; i++) {
            mComList.get(i).setOrder(i);
        }
        List<BmobObject> advs = new ArrayList<>(size);
        advs.addAll(mComList);
        new BmobBatch().updateBatch(advs).doBatch(new QueryListListener<BatchResult>() {

            @Override
            public void done(List<BatchResult> o, BmobException e) {
                if (e == null) {
                    for (int i = 0; i < o.size(); i++) {
                        BatchResult result = o.get(i);
                        BmobException ex = result.getError();
                        if (ex != null) {
                            showToast("第" + i + "个数据批量更新失败：" + ex.getMessage() + "," + ex.getErrorCode());
                        }
                    }
                    showToast("列表顺序更新完成");
                } else {
                    showToast("列表顺序更新失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                mRefreshLayout.beginRefreshing();
            }
        }
    }
}
